package com.yuelao.yuelao_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuelao.yuelao_backend.entity.SystemConfig;
import com.yuelao.yuelao_backend.mapper.SystemConfigMapper;
import com.yuelao.yuelao_backend.service.SystemConfigService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * 系统配置服务实现类
 */
@Slf4j
@Service
public class SystemConfigServiceImpl extends ServiceImpl<SystemConfigMapper, SystemConfig> 
        implements SystemConfigService {

    // 配置缓存：groupName -> (configKey -> configValue)
    private final Map<String, Map<String, String>> configCache = new ConcurrentHashMap<>();

    @Override
    public String getConfigValue(String configKey) {
        LambdaQueryWrapper<SystemConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SystemConfig::getConfigKey, configKey);
        SystemConfig config = getOne(wrapper);
        return config != null ? config.getConfigValue() : null;
    }

    @Override
    public String getConfigValue(String configKey, String defaultValue) {
        String value = getConfigValue(configKey);
        return value != null ? value : defaultValue;
    }

    @Override
    public Map<String, String> getConfigValues(List<String> configKeys) {
        if (CollectionUtils.isEmpty(configKeys)) {
            return new HashMap<>();
        }

        LambdaQueryWrapper<SystemConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(SystemConfig::getConfigKey, configKeys);
        List<SystemConfig> configs = list(wrapper);

        return configs.stream()
                .collect(Collectors.toMap(SystemConfig::getConfigKey, SystemConfig::getConfigValue));
    }

    @Override
    public boolean setConfigValue(String configKey, String configValue, String description, String groupName) {
        LambdaQueryWrapper<SystemConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SystemConfig::getConfigKey, configKey);
        SystemConfig existingConfig = getOne(wrapper);

        if (existingConfig != null) {
            // 更新现有配置
            existingConfig.setConfigValue(configValue);
            existingConfig.setDescription(description);
            existingConfig.setGroupName(groupName);
            return updateById(existingConfig);
        } else {
            // 创建新配置
            SystemConfig newConfig = new SystemConfig();
            newConfig.setConfigKey(configKey);
            newConfig.setConfigValue(configValue);
            newConfig.setDescription(description);
            newConfig.setGroupName(groupName);
            return save(newConfig);
        }
    }

    @Override
    public boolean updateConfigValue(String configKey, String configValue, String description) {
        LambdaQueryWrapper<SystemConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SystemConfig::getConfigKey, configKey);
        SystemConfig existingConfig = getOne(wrapper);

        if (existingConfig != null) {
            existingConfig.setConfigValue(configValue);
            if (description != null) {
                existingConfig.setDescription(description);
            }
            return updateById(existingConfig);
        }
        return false;
    }

    @Override
    public boolean deleteConfig(String configKey) {
        LambdaQueryWrapper<SystemConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SystemConfig::getConfigKey, configKey);
        return remove(wrapper);
    }

    @Override
    public List<SystemConfig> getConfigsByGroup(String groupName) {
        LambdaQueryWrapper<SystemConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SystemConfig::getGroupName, groupName);
        return list(wrapper);
    }

    @Override
    public String getCachedConfigValue(String groupName, String configKey, String defaultValue) {
        // 确保该分组的缓存已加载
        Map<String, String> groupCache = configCache.computeIfAbsent(groupName, this::loadGroupConfig);
        return groupCache.getOrDefault(configKey, defaultValue);
    }

    @Override
    public int getCachedConfigInt(String groupName, String configKey, int defaultValue) {
        String value = getCachedConfigValue(groupName, configKey, null);
        if (value == null) {
            return defaultValue;
        }
        try {
            return Integer.parseInt(value);
        } catch (NumberFormatException e) {
            log.warn("配置值解析为整数失败: groupName={}, configKey={}, value={}", groupName, configKey, value);
            return defaultValue;
        }
    }

    @Override
    public void refreshCache(String groupName) {
        log.info("刷新配置缓存: groupName={}", groupName);
        configCache.put(groupName, loadGroupConfig(groupName));
    }

    @Override
    public void clearAllCache() {
        log.info("清除所有配置缓存");
        configCache.clear();
    }

    /**
     * 从数据库加载指定分组的所有配置
     */
    private Map<String, String> loadGroupConfig(String groupName) {
        log.debug("从数据库加载配置: groupName={}", groupName);
        List<SystemConfig> configs = getConfigsByGroup(groupName);
        Map<String, String> result = new ConcurrentHashMap<>();
        for (SystemConfig config : configs) {
            result.put(config.getConfigKey(), config.getConfigValue());
        }
        return result;
    }
}